//
//  WorkHomeVC.m
//  XLDoctor
//
//  Created by longma on 2018/7/27.
//  Copyright © 2018年 XLH. All rights reserved.
//mj验证码

#import "EnterCodeController.h"
#import "CodeInputView.h"
#import "PersonalInfoController.h"
#import "MJUILoadingView.h"
#import "SetLoginPasswordVC.h"
#import "EmailCodeVC.h"
#import "LoginViewController.h"
#import "RegisterEmailVC.h"
#import "RegisterViewController.h"
#import "EmailForgotPasswordVC.h"
#import "ForgotPasswordVC.h"
#import "AccountVerificationVC.h"

@interface EnterCodeController ()
@property (weak, nonatomic) IBOutlet UIButton *codeButton;
@property (weak, nonatomic) IBOutlet UIView *codeBgView;
@property (nonatomic, strong) CodeInputView * codeView;
@property (weak, nonatomic) IBOutlet UILabel *tipLabel;
@property (weak, nonatomic) IBOutlet MJUILoadingView *loadingView;
@property (weak, nonatomic) IBOutlet UILabel *invalidCodeLabel;
@property (weak, nonatomic) IBOutlet UILabel *noReceiveLabel;

@end

@implementation EnterCodeController


- (void)viewDidLoad {
    [super viewDidLoad];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

- (void)mj_setUI{
    [super mj_setUI];
    
    [self.codeButton mj_createTimerWithDuration:60];
    [self.codeBgView addSubview:self.codeView];
    
    NSString *code = [NSString stringWithFormat:@"+%@%@",self.countryAreaCode[@"区号"],self.phone];
    
    if(self.email){
        code = self.email;
    }
    
    NSString *text = MJUILocalizedString(@"A text message with a 4-digit verification code was just sent to");
    self.tipLabel.text = [NSString stringWithFormat:@"%@ %@",text,code];
    
    [self.tipLabel mj_paragraphStyleWithArrString:@[code] font:nil color:UIColor.mj_appColor lineSpacing:4];
    [RoyHud showCenterToast:MJUILocalizedString(@"Verification code has been sent")];
    
    self.loadingView.loadImageView.image = [MJUIImageMake(@"icon_loading") mj_imageChangeColor:UIColor.mj_appColor];
    self.loadingView.loadImageViewH.constant = 25;
    
    //
    MJWeakSelf
    [self.noReceiveLabel mj_addTapActionWithBlock:^{
        [weakSelf handleNoReceiveButtonClick];
    }];
    
    [self updateUI];
}

#pragma mark - 方法
- (void)updateUI {
    NSString *phoneString = @"Didn't receive? Try phone verification";
    NSString *emailString = @"Didn't receive? Try email verification";
    
    if(self.captchaCodeType == CaptchaCodeTypeLogin){
        self.noReceiveLabel.mj_localizable = emailString;
    }
    else if(self.captchaCodeType == CaptchaCodeTypeEmailLogin){
        self.noReceiveLabel.mj_localizable = phoneString  ;
    }
    else if(self.captchaCodeType == CaptchaCodeTypeRegister){
        self.noReceiveLabel.mj_localizable = emailString;
    }
    else if(self.captchaCodeType == CaptchaCodeTypeEmailRegister){
        self.noReceiveLabel.mj_localizable = phoneString;
    }
    else if(self.captchaCodeType == CaptchaCodeTypeForgotPassword){
        self.noReceiveLabel.mj_localizable = emailString;
        UserModel *userModel = UserManager.shared.userModel;
        if(userModel && !userModel.email){
            self.noReceiveLabel.hidden = true;
        }
    }
    else if(self.captchaCodeType == CaptchaCodeTypeEmailForgotPassword){
        self.noReceiveLabel.mj_localizable = phoneString;
        UserModel *userModel = UserManager.shared.userModel;
        if(userModel && !userModel.phoneNumber){
            //登录状态忘记密码
            self.noReceiveLabel.hidden = true;
        }
    }else{
        self.noReceiveLabel.hidden = true;
    }
  
}
- (void)handleNoReceiveButtonClick {
    
    if(self.captchaCodeType == CaptchaCodeTypeLogin){
        EmailCodeVC *vc = [[EmailCodeVC alloc]init];
        [self.navigationController pushViewController:vc animated:true];
    }
    else if(self.captchaCodeType == CaptchaCodeTypeEmailLogin){
        LoginViewController *vc = [[LoginViewController alloc]init];
        [self.navigationController pushViewController:vc animated:true];
    }
    else if(self.captchaCodeType == CaptchaCodeTypeRegister){
        RegisterEmailVC *vc = [[RegisterEmailVC alloc]init];
        [self.navigationController pushViewController:vc animated:true];
    }
    else if(self.captchaCodeType == CaptchaCodeTypeEmailRegister){
        RegisterViewController *vc = [[RegisterViewController alloc]init];
        [self.navigationController pushViewController:vc animated:true];
    }
    //
    else if(self.captchaCodeType == CaptchaCodeTypeForgotPassword){
        //登录状态下存在邮箱
        UserModel *userModel = UserManager.shared.userModel;
        if(userModel && userModel.email){
            AccountVerificationVC *vc = [[AccountVerificationVC alloc]init];
            vc.email = userModel.email;
            [self.navigationController pushViewController:vc animated:true];
        }else{
            EmailForgotPasswordVC *vc = [[EmailForgotPasswordVC alloc]init];
            [self.navigationController pushViewController:vc animated:true];
        }
        
    }
    else if(self.captchaCodeType == CaptchaCodeTypeEmailForgotPassword){
        //登录状态下存在手机号码
        UserModel *userModel = UserManager.shared.userModel;
        if(userModel && userModel.phoneNumber){
            AccountVerificationVC *vc = [[AccountVerificationVC alloc]init];
            vc.phoneNumber = userModel.phoneNumber;
            [self.navigationController pushViewController:vc animated:true];
        }else{
            ForgotPasswordVC *vc = [[ForgotPasswordVC alloc]init];
            [self.navigationController pushViewController:vc animated:true];
        }
    }
  
}

- (IBAction)handleCodeButtonClick:(UIButton *)sender {
   
    [self.codeView endEdit];
    MJWeakSelf
    if(self.phone){
        [HealthHelper showCaptchaViewWithPhoneNumber:self.phone countryAreaCode:self.countryAreaCode completion:^(MJBaseModel *model) {
            if(model.code == 200){
                [weakSelf.codeButton mj_createTimerWithDuration:60];
            }
        }];
    }else{
        [HealthHelper showCaptchaViewWithEmail:self.email completion:^(MJBaseModel *model) {
            if(model.code == 200){
                [weakSelf.codeButton mj_createTimerWithDuration:60];
            }
        }];
    }
    
}
- (void)loginWithCode:(NSString *)code{
    
    [self.loadingView startAnimation];
    self.invalidCodeLabel.hidden = true;
    
    MJWeakSelf
    if(self.captchaCodeType == CaptchaCodeTypeChangePhone || self.captchaCodeType == CaptchaCodeTypeChangeEmail){
        NSString *url = user_changPhone;
        NSDictionary *params = @{};
        if(self.captchaCodeType == CaptchaCodeTypeChangePhone){
            NSDictionary *param =  @{
                @"countryCode": self.countryAreaCode[@"区号"],
                @"phoneNumber": self.phone,
                @"region": self.countryAreaCode[@"ISO"],
                @"code": code,
            };
            params = param;
            url = user_changPhone;
        }
        if(self.captchaCodeType == CaptchaCodeTypeChangeEmail){
            NSDictionary *param =  @{
                @"email": self.email,
                @"code": code
            };
            params = param;
            url = user_changEmail;
        }
        
        [MJHttpNetWorking requestWithParams:params requestUri:url requestType:RequestTypePut showLoading:false success:^(MJBaseModel *model) {
            
            [weakSelf.loadingView stopAnimation];

            if(model.code == 417){
                weakSelf.invalidCodeLabel.hidden = false;
                [weakSelf.codeView showErrorType];
            }else if(model.code == 412){
                [RoyHud showToast:MJUILocalizedString(@"Phone number already in use")];
            }else if(model.code == 200){
                if(model.data){
                    [UserManager.shared saveUserInfo:model.data];
                }
                [RoyHud showToast:MJUILocalizedString(@"Setting successful")];
                [weakSelf popViewControllerWithTargetArr:@[@"AccountSecurityVC"] WaitThread:false];
            }

        } failure:^(NSError *error) {
            [weakSelf.loadingView stopAnimation];

        }];
    }else if(self.captchaCodeType == CaptchaCodeTypeForgotPassword || self.captchaCodeType == CaptchaCodeTypeEmailForgotPassword){
        NSString *url = user_verifyEmailCode;
        NSDictionary *params = @{};
        if(self.captchaCodeType == CaptchaCodeTypeForgotPassword){
            NSDictionary *param =  @{
                @"countryCode": self.countryAreaCode[@"区号"],
                @"phoneNumber": self.phone,
                @"region": self.countryAreaCode[@"ISO"],
                @"code": code,
            };
            params = param;
            url = user_verifyCode;
        }
        if(self.captchaCodeType == CaptchaCodeTypeEmailForgotPassword){
            NSDictionary *param =  @{
                @"email": self.email,
                @"code": code
            };
            params = param;
            url = user_verifyEmailCode;
        }
        [MJHttpNetWorking requestWithParams:params requestUri:url requestType:RequestTypePost showLoading:false success:^(MJBaseModel *model) {
            
            [weakSelf.loadingView stopAnimation];

            if(model.code == 417){
                weakSelf.invalidCodeLabel.hidden = false;
                [weakSelf.codeView showErrorType];
            }else if(model.code == 200){
                
                NSNumber *data = (NSNumber *)model.data;
                BOOL dataFlag = [data boolValue];
                if(dataFlag){
                    SetLoginPasswordVC *vc = [[SetLoginPasswordVC alloc]init];
                    vc.forgotPasswordParams = params;
                    [weakSelf.navigationController pushViewController:vc animated:true];
                }else{
                    weakSelf.invalidCodeLabel.hidden = false;
                    [weakSelf.codeView showErrorType];
                }
            }

        } failure:^(NSError *error) {
            [weakSelf.loadingView stopAnimation];

        }];
        
        
    }else if(self.captchaCodeType == CaptchaCodeTypeLogin || self.captchaCodeType == CaptchaCodeTypeRegister){
        NSDictionary *params =  @{
            @"countryCode": self.countryAreaCode[@"区号"],
            @"phoneNumber": self.phone,
            @"region": self.countryAreaCode[@"ISO"],
            @"loginType": @"iOS",
            @"code": code,
            @"isRegister": @(self.captchaCodeType == CaptchaCodeTypeRegister ? true:false)
        };
        [MJHttpNetWorking requestWithParams:params requestUri:user_login requestType:RequestTypePost showLoading:false success:^(MJBaseModel *model) {
            [weakSelf.loadingView stopAnimation];

            if(model.code == 417){
                weakSelf.invalidCodeLabel.hidden = false;
                [weakSelf.codeView showErrorType];
            }else if(model.code == 200){
                
                UserModel *userModel = [UserModel yy_modelWithDictionary:model.data];
                
                [UserManager.shared saveUserInfo:model.data];
                
                if(weakSelf.captchaCodeType == CaptchaCodeTypeRegister){
                    
                    //跳转设置密码
                    SetLoginPasswordVC *vc = [[SetLoginPasswordVC alloc]init];
                    vc.isRegister = true;
                    [weakSelf.navigationController pushViewController:vc animated:true];
                    
                    
//                    if(userModel.userName.length){
//                        AppDelegate *appDelegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
//                        [appDelegate initRootViewController];
//                        [RoyHud showToast:MJUILocalizedString(@"Log in successful")];
//
//                    }else{
//                        PersonalInfoController *vc = [[PersonalInfoController alloc]init];
//                        [weakSelf.navigationController pushViewController:vc animated:true];
//                        [RoyHud showToast:MJUILocalizedString(@"Sign up successful")];
//                    }
                }else{
                    AppDelegate *appDelegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
                    [appDelegate initRootViewController];
                    [RoyHud showToast:MJUILocalizedString(@"Log in successful")];

                }
            }

        } failure:^(NSError *error) {
            [weakSelf.loadingView stopAnimation];

        }];
    }else if(self.captchaCodeType == CaptchaCodeTypeEmailRegister || self.captchaCodeType == CaptchaCodeTypeEmailLogin){
        NSDictionary *params =  @{
            @"email": self.email,
            @"loginType": @"iOS",
            @"code": code,
            @"isRegister": @(self.captchaCodeType == CaptchaCodeTypeEmailRegister ? true:false)
        };
        [MJHttpNetWorking requestWithParams:params requestUri:user_emailLogin requestType:RequestTypePost showLoading:false success:^(MJBaseModel *model) {
            [weakSelf.loadingView stopAnimation];

            if(model.code == 417){
                weakSelf.invalidCodeLabel.hidden = false;
                [weakSelf.codeView showErrorType];
            }else if(model.code == 200){
                
                [UserManager.shared saveUserInfo:model.data];
                if(weakSelf.captchaCodeType == CaptchaCodeTypeEmailRegister){
                    //跳转设置密码
                    SetLoginPasswordVC *vc = [[SetLoginPasswordVC alloc]init];
                    vc.isRegister = true;
                    [weakSelf.navigationController pushViewController:vc animated:true];
                }else{
                    AppDelegate *appDelegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
                    [appDelegate initRootViewController];
                    [RoyHud showToast:MJUILocalizedString(@"Log in successful")];
                }
            }
        } failure:^(NSError *error) {
            [weakSelf.loadingView stopAnimation];

        }];
    }
}

#pragma mark - 代理

#pragma mark - 懒加载
- (CodeInputView *)codeView {
    MJWeakSelf
    if (!_codeView) {
        _codeView = [[CodeInputView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 50, 70) inputType:4 selectCodeBlock:^(NSString * code) {
            NSLog(@"code === %@",code);
            [weakSelf loginWithCode:code];
        }];
    }
    return _codeView;
}

@end
